package com.tool_stdy.Reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.commons.lang3.ArrayUtils;

import com.tool_stdy.Model.TeacherBean;

public class CopyObjectTest {

	public static Object copyObjedct(Object obj) throws Exception {
		Class<?> clazz = obj.getClass();
		Class<?> superclass = clazz.getSuperclass();
		Object newObject = clazz.newInstance();

		//父类和子类的所有字段
		Field[] fields = ArrayUtils.addAll(clazz.getDeclaredFields(),superclass.getDeclaredFields());
		for (Field f : fields) {
			String name = f.getName();
			String getMethodName = "get" + name.substring(0, 1).toUpperCase()+ name.substring(1);
			String setMethodName = "set" + name.substring(0, 1).toUpperCase()+ name.substring(1);
			Method method = clazz.getMethod(getMethodName, new Class[]{String.class});
			Object value = method.invoke(obj, new Object[]{});

			Method method2 = clazz.getMethod(setMethodName, f.getType());
			method2.invoke(newObject, value);
		}

		return newObject;
	}

	public static void main(String[] args) throws Exception {
		TeacherBean tea = new TeacherBean();
		tea.setClassNo(1);
		tea.setId(10);
		tea.setName("hello");

		TeacherBean newT = (TeacherBean) copyObjedct(tea);
		System.out.println(newT.getClassNo() + "--->" + newT.getId() + "-->"
				+ newT.getName());
	}
}
